package com.wakala.employment.fragment.other;

import static com.xuexiang.xui.utils.XToastUtils.toast;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.hjq.toast.Toaster;
import com.kongzue.dialogx.dialogs.CustomDialog;
import com.kongzue.dialogx.interfaces.OnBindView;
import com.tamsiree.rxkit.RxAppTool;
import com.tamsiree.rxkit.RxTool;
import com.tamsiree.rxkit.view.RxToast;
import com.wakala.employment.R;
import com.wakala.employment.activity.AddressMapActivity;
import com.wakala.employment.adapter.base.FlowTagSimpleAdapter;
import com.wakala.employment.adapter.bean.PoiEntity;
import com.wakala.employment.adapter.bean.UserAddress;
import com.wakala.employment.adapter.jobCategory.JobCategoryAttrTreeVo;
import com.wakala.employment.core.BaseFragment;
import com.wakala.employment.core.bean.EventKey;
import com.wakala.employment.core.constants.Constants;
import com.wakala.employment.core.http.subscriber.NoTipRequestSubscriber;
import com.wakala.employment.databinding.FragmentAddressSelectBinding;
import com.wakala.employment.fragment.recruit.RecruitIssueFragment;
import com.wakala.employment.http.TestApi;
import com.wakala.employment.http.bean.ResumeInfoVo;
import com.wakala.employment.http.bean.UserAddressPage;
import com.xuexiang.rxutil2.rxbus.RxBusUtils;
import com.xuexiang.xhttp2.XHttpProxy;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.enums.CoreAnim;
import com.xuexiang.xpage.utils.GsonUtils;
import com.xuexiang.xui.utils.XToastUtils;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xui.widget.flowlayout.FlowTagLayout;
import com.xuexiang.xutil.XUtil;
import com.xuexiang.xutil.common.StringUtils;
import com.xuexiang.xutil.net.JsonUtil;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link AddressSelectFragment#} factory method to
 * create an instance of this fragment.
 */
@Page(anim = CoreAnim.none)
public class AddressSelectFragment extends BaseFragment<FragmentAddressSelectBinding> implements View.OnClickListener {


    private static String TAG = "AddressSelectFragment";

    //---------------定位-----
    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new MyAMapLocationListener();
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;

    private Boolean isLocation = false;

    private UserAddress myUserAddress;

    //------------------------


    private ListView listView;

    private CommonAdapter<UserAddress> listViewAdapter;

    private List<UserAddress> userAddressList = new ArrayList<>();


    @NonNull
    @Override
    protected FragmentAddressSelectBinding viewBindingInflate(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, boolean attachToRoot) {
        return FragmentAddressSelectBinding.inflate(inflater, container, attachToRoot);
    }

    @Override
    protected TitleBar initTitle() {
        return super.initTitle().setTitle("地址选择");
    }

    @Override
    protected void initViews() {
        isLocation = true;
        listView = binding.listview;
        //创建适配器
        listViewAdapter = new CommonAdapter<UserAddress>(getContext(), R.layout.layout_simple_address_view, userAddressList) {

            @Override
            protected void convert(ViewHolder viewHolder, UserAddress userAddress, int i) {
                if (StringUtils.isEmpty(userAddress.getPoiName())) {
                    viewHolder.setText(R.id.tv_address_name, userAddress.getDetail());
                } else {
                    viewHolder.setText(R.id.tv_address_name, userAddress.getPoiName());
                }

                viewHolder.setText(R.id.tv_address_detail, userAddress.getProvince() + userAddress.getCity() + userAddress.getDistrict() + userAddress.getDetail());
                viewHolder.setOnClickListener(R.id.ll_content, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //选择当前地址并返回上一页
                        RxBusUtils.get().postRxEvent(EventKey.EVENT_ADDRESS_SELECTED,userAddress);
                        popToBack();
                    }
                });

            }
        };
        //listView绑定适配器
        listView.setAdapter(listViewAdapter);
        appLoadingDialog.show();
        //初始化定位
        initLocation();
        getUserAddressList();
    }

    @Override
    protected void initListeners() {
        super.initListeners();
        binding.layoutMyAddress.setOnClickListener(this);
        binding.btnSubmit.setOnClickListener(this);
        //查询地址历史
        binding.stvGoLication.setOnClickListener(this);
    }


    // 重写onActivityResult方法接收回传数据
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 101 && data != null) {
            String poiEntityStr = data.getStringExtra("poiEntity");
            // 处理回传的数据
            if (!StringUtils.isEmpty(poiEntityStr)) {
                PoiEntity poiEntity = JsonUtil.fromJson(poiEntityStr, PoiEntity.class);
                String fullAddress = poiEntity.getAddress();
                String title = poiEntity.getTitle();
                binding.tvMyAddressName.setText(title);
                binding.tvMyAddressDetail.setText(fullAddress);
                //
                UserAddress userAddress = new UserAddress();
                userAddress.setCity(poiEntity.getCityName());
                userAddress.setCityId(Integer.valueOf(poiEntity.getCityCode()));
                userAddress.setProvince(poiEntity.getProvinceName());
                userAddress.setDistrict(poiEntity.getAdName());
                userAddress.setLatitude(poiEntity.getLat());
                userAddress.setLongitude(poiEntity.getLon());
                userAddress.setDetail(poiEntity.getSnippet());
                userAddress.setPoiName(poiEntity.getTitle());
                myUserAddress = JsonUtil.fromJson(GsonUtils.toJson(userAddress),UserAddress.class);
                //设置地址信息

            }
        }
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.stv_go_lication) {
            //点击点位
            if (XXPermissions.isGranted(getContext(), Permission.ACCESS_FINE_LOCATION)) {
                //已获取定位权限
                Intent intent = new Intent(getContext(), AddressMapActivity.class);
                startActivityForResult(intent, Constants.REQ_RESULT_101);
            } else {
                checkLocationPermission();
            }

        } else if (id == R.id.layout_my_address) {
            if(null!=myUserAddress){
                RxBusUtils.get().postRxEvent(EventKey.EVENT_ADDRESS_SELECTED,myUserAddress);
                popToBack();
            }else {
                RxToast.warning("定位地址失败");
            }

        } else if (id == R.id.btn_submit) {
            popToBack();
        }
    }

    //--------------------------//

    /**
     * 定位 //初始化定位
     */
    private void initLocation() {
        if (!isLocation) return;
        try {
            AMapLocationClient.updatePrivacyShow(getContext(), true, true);
            AMapLocationClient.updatePrivacyAgree(getContext(), true);
            mLocationClient = new AMapLocationClient(getContext());
        } catch (Exception e) {
            e.printStackTrace();
            appLoadingDialog.dismiss();
            Toaster.show("定位失败，请检查手机定位授权情况");
        }
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //获取一次定位结果：
        //该方法默认为false。
        mLocationOption.setOnceLocation(false);

        //获取最近3s内精度最高的一次定位结果：
        //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
        mLocationOption.setOnceLocationLatest(true);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //关闭缓存机制
        mLocationOption.setLocationCacheEnable(false);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        //检查定位授权情况
        checkLocationPermission();
    }

    /**
     * 定位监听
     */
    private class MyAMapLocationListener implements AMapLocationListener {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if (aMapLocation != null) {
                if (aMapLocation.getErrorCode() == 0) {
                    appLoadingDialog.dismiss();
                    Log.e(TAG + "-位置：", aMapLocation.getAddress());
                    String address = aMapLocation.getAddress();
                    String poiName = aMapLocation.getPoiName();
                    String province = aMapLocation.getProvince();
                    String city = aMapLocation.getCity();
                    String cityCode = aMapLocation.getCityCode();
                    String district = aMapLocation.getDistrict();
                    String locationDetail = address;
                    binding.tvMyAddressName.setText(poiName);
                    binding.tvMyAddressDetail.setText(address);
                    String fullAddress = locationDetail;
                    String title = poiName;
                    binding.tvMyAddressName.setText(title);
                    binding.tvMyAddressDetail.setText(fullAddress);
                    //
                    UserAddress userAddress = new UserAddress();
                    userAddress.setCity(city);
                    userAddress.setCityId(Integer.valueOf(aMapLocation.getCityCode()));
                    userAddress.setProvince(province);
                    userAddress.setDistrict(district);
                    userAddress.setLatitude(String.valueOf(aMapLocation.getLatitude()));
                    userAddress.setLongitude(String.valueOf(aMapLocation.getLongitude()));
                    userAddress.setDetail(address);
                    userAddress.setPoiName(poiName);
                    myUserAddress = JsonUtil.fromJson(GsonUtils.toJson(userAddress),UserAddress.class);
                    mLocationClient.stopLocation();

                } else {
                    mLocationClient.stopLocation();
                    Toaster.show("定位失败");
                    appLoadingDialog.dismiss();
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    String error = "location Error, ErrCode:"
                            + aMapLocation.getErrorCode() + ", errInfo:"
                            + aMapLocation.getErrorInfo();
                    Toaster.show("定位失败");
                    Log.e("AmapError", "location Error, ErrCode:"
                            + aMapLocation.getErrorCode() + ", errInfo:"
                            + aMapLocation.getErrorInfo());
                }
            }
        }
    }

    private void checkLocationPermission() {
        //检查是否获取了定位权限
        if (XXPermissions.isGranted(getContext(), Permission.ACCESS_FINE_LOCATION)) {
            //已获取定位权限
            mLocationClient.startLocation();
        } else {
            appLoadingDialog.dismiss();
            CustomDialog.show(new OnBindView<CustomDialog>(R.layout.layout_custom_location_dialog) {
                @Override
                public void onBind(final CustomDialog dialog, View v) {
                    Button btnOk;
                    btnOk = v.findViewById(R.id.btn_ok);
                    TextView textClose = v.findViewById(R.id.btn_close);
                    TextView textContent = v.findViewById(R.id.tv_content);
                    textContent.setText("需要访问您的位置才能确定发布的职位地址");
                    textClose.setOnClickListener(view -> dialog.dismiss());
                    btnOk.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            //申请权限
                            applyLocationPermission();
                            dialog.dismiss();
                        }
                    });
                }
            }).setMaskColor(getResources().getColor(R.color.translucent_background));
        }
    }

    private void applyLocationPermission() {
        XXPermissions.with(this)
                // 申请单个权限
                .permission(Permission.ACCESS_FINE_LOCATION)
                .request(new OnPermissionCallback() {

                    @Override
                    public void onGranted(@NonNull List<String> permissions, boolean allGranted) {
                        if (!allGranted) {
                            toast("获取部分权限成功，但部分权限未正常授予");
                            return;
                        }
                        Toaster.show("已获取位置权限");
                        mLocationClient.startLocation();
                    }

                    @Override
                    public void onDenied(@NonNull List<String> permissions, boolean doNotAskAgain) {
                        appLoadingDialog.dismiss();
                        if (doNotAskAgain) {
                            toast("被拒绝授权，请手动开启位置权限");
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(getContext(), permissions);
                        } else {
                            toast("获取位置权限失败");
                        }
                    }
                });
    }

    /**
     * 查询用户历史地址列表
     */
    @SuppressLint("CheckResult")
    private void getUserAddressList() {
        appLoadingDialog.show();
        XHttpProxy.proxy(TestApi.IUserService.class)
                .userAddressList()
                .subscribeWith(new NoTipRequestSubscriber<UserAddressPage>() {
                    @Override
                    protected void onSuccess(UserAddressPage userAddressPage) {
                        Log.i(TAG, "-------------地址列表信息详情------------------");
                        Log.i(TAG, GsonUtils.toJson(userAddressPage));
                        userAddressList.clear();
                        userAddressList.addAll(userAddressPage.getList());
                        //listViewAdapter.notifyDataSetChanged();
                        XUtil.runOnUiThread(() -> {
                            listViewAdapter.notifyDataSetChanged();
                        });
                        if (userAddressPage.getList().isEmpty()) {
                            //显示空提示
                            binding.ltNoAddressTip.setVisibility(View.VISIBLE);
                        } else {
                            binding.ltNoAddressTip.setVisibility(View.GONE);
                        }
                        Log.i(TAG, "-------------地址列表信息详情------------------");
                        //绑定数据到页面控件
                        appLoadingDialog.dismiss();
                    }

                    @Override
                    public void onError(ApiException e) {
                        super.onError(e);
                        Log.i(TAG, "-------------地址列表信息详情-返回错误------------------");
                        Log.e(TAG, e.getMessage());
                        appLoadingDialog.dismiss();
                    }

                });
    }
}